import { NetServices } from "./NetServices";
import { GetTypeOf } from "../../../Decorator/Decorator";
import { SerializeHelper } from "../../Serialize/SerializeHelper";

export class MessageSerializeHelper {

    private static GetStream(count: number = 0) {
        const buffer = new ArrayBuffer(count);
        const view = new DataView(buffer);
        return view;
    }

    public static MessageToStream(message: Object) {
        let type = GetTypeOf(message);
        let opcode = NetServices.Instance.GetOpcode(type);

        let buffer = SerializeHelper.Serialize(type, message as Buffer);
        let stream = this.GetStream(4 + buffer.byteLength);

        stream.setInt32(0, opcode);
        let len = buffer.length;
        for (let i = 0; i < len; i++) {
            let uint8 = buffer[i];
            stream.setUint8(4 + i, uint8);
        }
        // console.log(`MessageToStream`);
        // console.log(type);
        // console.log(opcode);
        // console.log(stream.buffer as Buffer);
        // console.log(buffer);

        return { opcode, stream };
    }

}